/**
 * 数据同步任务专用进度Hook
 * 基于通用进度通知系统，为数据同步任务提供专门的进度管理功能
 */

import { useCallback } from 'react';
import { useProgressNotification } from './useProgressNotification';

// 数据同步任务进度Hook
export const useSyncTaskProgress = () => {
  // 使用通用进度通知系统
  const progressHook = useProgressNotification();

  /**
   * 启动数据同步任务进度监控
   * @param taskName 任务名称
   * @param sourceType 源数据类型
   * @param targetType 目标数据类型
   * @returns 通知ID
   */
  const startSyncTask = useCallback((
    taskName: string,
    sourceType: string,
    targetType: string
  ) => {
    return progressHook.start({
      type: 'progress',
      title: '初始化同步', // 收缩状态显示当前状态
      description: `${taskName} (${sourceType} → ${targetType})`, // 展开状态显示任务名称和路径
      category: 'data-sync',
      source: sourceType,
      target: targetType,
      metadata: {
        taskName,
        sourceType,
        targetType
      },
      config: {
        persistent: true,
        autoClose: false,
        showProgress: true,
        showTimestamp: true,
        showEstimatedTime: true,
        showSpeed: true,
        showStatistics: true,
        priority: 7, // 比数据血缘稍高的优先级
      },
    });
  }, [progressHook]);

  /**
   * 更新同步任务进度
   * @param id 通知ID
   * @param progress 进度百分比 (0-100)
   * @param currentStage 当前阶段描述
   * @param processedRecords 已处理记录数
   * @param totalRecords 总记录数
   * @param statistics 统计信息
   */
  const updateSyncProgress = useCallback((
    id: string,
    progress: number,
    currentStage: string,
    processedRecords: number = 0,
    totalRecords: number = 0,
    statistics?: Record<string, any>
  ) => {
    const progressInfo = {
      current: Math.round(progress),
      total: 100,
      processed: processedRecords,
      remaining: totalRecords - processedRecords,
      estimatedTime: statistics?.estimatedTimeRemaining || 0,
    };

    // 构建收缩状态的标题（当前状态 + 进度）
    const compactTitle = progress > 0
      ? `${currentStage} ${Math.round(progress)}%`
      : currentStage;

    // 构建展开状态的描述（任务名称 + 详细进度）
    const taskName = statistics?.taskName || '数据同步任务';
    const sourceType = statistics?.sourceType || 'Unknown';
    const targetType = statistics?.targetType || 'Unknown';
    const expandedDescription = `${taskName} (${sourceType} → ${targetType}) - ${processedRecords.toLocaleString()}/${totalRecords.toLocaleString()} 条记录`;



    progressHook.updateProgress(id, {
      title: compactTitle, // 更新标题为当前状态
      description: expandedDescription, // 更新描述为详细信息
      progress: Math.round(progress),
      progressInfo,
      currentStage,
      currentItem: `${processedRecords}/${totalRecords} 条记录`,
      statistics: {
        processedRecords,
        totalRecords,
        successRecords: statistics?.successRecords || 0,
        failedRecords: statistics?.failedRecords || 0,
        currentBatch: statistics?.currentBatch || 0,
        totalBatches: statistics?.totalBatches || 0,
        taskName,
        sourceType,
        targetType,
        ...statistics
      },
    });
  }, [progressHook]);

  /**
   * 完成同步任务
   * @param id 通知ID
   * @param success 是否成功
   * @param summary 完成摘要
   * @param statistics 最终统计信息
   */
  const completeSyncTask = useCallback((
    id: string,
    success: boolean,
    summary?: string,
    statistics?: Record<string, any>
  ) => {
    const finalSummary = summary || (success
      ? `同步完成：处理 ${statistics?.processedRecords || 0} 条记录`
      : '同步失败');



    progressHook.complete(id, {
      success,
      summary: finalSummary,
      statistics: {
        processed: statistics?.processedRecords || 0,
        success: statistics?.successRecords || 0,
        failed: statistics?.failedRecords || 0,
        duration: statistics?.duration || 0,
        ...statistics
      },
    });
  }, [progressHook]);

  /**
   * 暂停同步任务
   * @param id 通知ID
   */
  const pauseSyncTask = useCallback((id: string) => {
    progressHook.pause(id);
  }, [progressHook]);

  /**
   * 恢复同步任务
   * @param id 通知ID
   */
  const resumeSyncTask = useCallback((id: string) => {
    progressHook.resume(id);
  }, [progressHook]);

  /**
   * 取消同步任务
   * @param id 通知ID
   * @param reason 取消原因
   */
  const cancelSyncTask = useCallback((
    id: string,
    reason?: string
  ) => {
    progressHook.cancel(id, reason);
  }, [progressHook]);

  /**
   * 同步任务失败
   * @param id 通知ID
   * @param error 错误信息
   */
  const failSyncTask = useCallback((
    id: string,
    error: { message: string; code?: string; details?: any }
  ) => {
    progressHook.fail(id, error);
  }, [progressHook]);

  return {
    startSyncTask,
    updateSyncProgress,
    completeSyncTask,
    pauseSyncTask,
    resumeSyncTask,
    cancelSyncTask,
    failSyncTask,
  };
};

// 导出类型定义
export type SyncTaskProgressHook = ReturnType<typeof useSyncTaskProgress>;
